#!/bin/bash

S3SYNC_DIR='/Users/sdd/Desktop/GLP/CLEAN.development/Bigstore/s3sync.rb'
S3CMD_BIN="${S3SYNC_DIR}/s3cmd.rb"
BUCKET='glp-rec-library-beta'
BASE_URL='http://commondatastorage.googleapis.com'
export AWS_S3_HOST='commondatastorage.googleapis.com'
export AWS_ACCESS_KEY_ID='GOOGXOJMU54PUTLIDQBR'
export AWS_SECRET_ACCESS_KEY='5dWeEPo2GjVdU7FHF8PhlrfxsmDLaIiHAs8YHsWm'

echo 'Verifying file types...'
find ${1}/ -type f | while read src; do
    ext=`echo ${src} | sed 's/^.*\.//'`
    case ${ext} in
	doc) mime_type='application/msword';;
	docx) mime_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document';;
	pptx) mime_type='application/vnd.openxmlformats-officedocument.presentationml.presentation';;
	xlsx) mime_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';;
	pdf) mime_type='application/pdf';;
	swf) mime_type='application/x-shockwave-flash';;
	xls) mime_type='application/vnd.ms-excel';;
	zip) mime_type='application/zip';;
	*) echo "Unknown extension: ${ext}"; exit 3;;
    esac
done

echo 'Determining next id...'
YES_FILE=`mktemp -t /tmp`
cat > ${YES_FILE} <<EOF
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
EOF
index=`${S3CMD_BIN} list glp-rec-library-beta < ${YES_FILE} | grep 'rec-03' | sed 's/^rec-0*//;s/-.*//' | sort -un | tail -1`
if [[ -z "${index}" ]]; then
    index=299999
fi
index=$((${index} + 1))

echo 'Uploading files...'
find ${1}/ -type f | while read src; do
    ext=`echo ${src} | sed 's/^.*\.//'`
    dst="rec-0${index}-XXX.${ext}"
    # TODO(sdd): This should be a function.
    case ${ext} in
	doc) mime_type='application/msword';;
	docx) mime_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document';;
	pptx) mime_type='application/vnd.openxmlformats-officedocument.presentationml.presentation';;
	xlsx) mime_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';;
	pdf) mime_type='application/pdf';;
	swf) mime_type='application/x-shockwave-flash';;
	xls) mime_type='application/vnd.ms-excel';;
	zip) mime_type='application/zip';;
	*) echo "Unknown extension: ${ext}"; exit 3;;
    esac
    file_name=`basename "${src}"`
    headers="'x-amz-meta-GLP-Source-URI: file://${file_name}' 'Content-Type: ${mime_type}' 'x-amz-acl:public-read'"
    echo "Uploading ${src} => ${dst}..."
    cmd="${S3CMD_BIN} put ${BUCKET}:${dst} '${src}' ${headers}"
    echo ${cmd}
    eval ${cmd}
    index=$((${index} + 1))
done
